/**
 * 远程文件浏览器
 * 负责连接远程服务器并提供文件浏览、下载、上传等功能
 * 
 * @author lihengtt <lihengsir@gmail.com>
 * @github https://github.com/lihengtt
 */

import * as vscode from 'vscode';
import * as path from 'path';
import { ConfigManager } from './configManager';
import { DeploymentManager } from './deploymentManager';

export interface RemoteFile {
    name: string;
    path: string;
    isDirectory: boolean;
    size?: number;
    modifiedTime?: Date;
    permissions?: string;
}

export interface RemoteFileResult {
    success: boolean;
    files?: RemoteFile[];
    error?: string;
}

export class RemoteExplorer {
    private configManager: ConfigManager;
    private deploymentManager: DeploymentManager;
    private outputChannel: vscode.OutputChannel;
    private currentRemotePath: string = '/';

    /**
     * 构造函数
     * @param configManager - 配置管理器实例
     * @param deploymentManager - 部署管理器实例
     * @author lihengtt <lihengsir@gmail.com>
     */
    constructor(configManager: ConfigManager, deploymentManager: DeploymentManager) {
        this.configManager = configManager;
        this.deploymentManager = deploymentManager;
        this.outputChannel = vscode.window.createOutputChannel('Remote Explorer');
        this.initializeRemotePath();
    }

    /**
     * 初始化远程路径，使用配置中的remotePath作为起始目录
     * @author lihengtt <lihengsir@gmail.com>
     */
    private initializeRemotePath(): void {
        const config = this.configManager.getConfig();
        if (config && config.remotePath) {
            this.currentRemotePath = config.remotePath;
        }
    }

    /**
     * 列出远程目录内容
     * @param remotePath - 远程路径
     * @returns Promise<RemoteFileResult>
     * @author lihengtt <lihengsir@gmail.com>
     */
    async listRemoteFiles(remotePath?: string): Promise<RemoteFileResult> {
        const config = this.configManager.getConfig();
        if (!config) {
            return { success: false, error: '请先配置服务器连接信息' };
        }

        const targetPath = remotePath || this.currentRemotePath;
        this.outputChannel.appendLine(`列出远程目录: ${targetPath}`);

        try {
            const files = await this.deploymentManager.listFiles(targetPath);
            this.currentRemotePath = targetPath;
            return { success: true, files };
        } catch (error) {
            const errorMsg = `列出远程文件时发生错误: ${error}`;
            this.outputChannel.appendLine(errorMsg);
            return { success: false, error: errorMsg };
        }
    }

    /**
     * 创建远程目录
     * @param remotePath - 远程目录路径
     * @returns Promise<boolean>
     * @author lihengtt <lihengsir@gmail.com>
     */
    async createRemoteDirectory(remotePath: string): Promise<boolean> {
        const config = this.configManager.getConfig();
        if (!config) {
            vscode.window.showErrorMessage('请先配置服务器连接信息');
            return false;
        }

        this.outputChannel.appendLine(`创建远程目录: ${remotePath}`);

        try {
            const success = await this.deploymentManager.createRemoteDirectory(remotePath);
            
            if (success) {
                this.outputChannel.appendLine(`远程目录创建成功: ${remotePath}`);
                vscode.window.showInformationMessage(`目录创建成功: ${path.basename(remotePath)}`);
                return true;
            } else {
                this.outputChannel.appendLine(`远程目录创建失败`);
                vscode.window.showErrorMessage(`目录创建失败`);
                return false;
            }
        } catch (error) {
            const errorMsg = `创建远程目录时发生错误: ${error}`;
            this.outputChannel.appendLine(errorMsg);
            vscode.window.showErrorMessage(errorMsg);
            return false;
        }
    }

    /**
     * 删除远程文件或目录
     * @param remotePath - 远程文件路径
     * @param isDirectory - 是否为目录
     * @returns Promise<boolean>
     * @author lihengtt <lihengsir@gmail.com>
     */
    async deleteRemoteFile(remotePath: string, isDirectory: boolean = false): Promise<boolean> {
        const config = this.configManager.getConfig();
        if (!config) {
            vscode.window.showErrorMessage('请先配置服务器连接信息');
            return false;
        }

        // 确认删除
        const confirmMessage = isDirectory ? 
            `确定要删除远程目录 "${path.basename(remotePath)}" 及其所有内容吗？` :
            `确定要删除远程文件 "${path.basename(remotePath)}" 吗？`;
        
        const choice = await vscode.window.showWarningMessage(
            confirmMessage,
            { modal: true },
            '确定删除',
            '取消'
        );

        if (choice !== '确定删除') {
            return false;
        }

        this.outputChannel.appendLine(`删除远程${isDirectory ? '目录' : '文件'}: ${remotePath}`);

        try {
            const success = await this.deploymentManager.deleteRemoteFile(remotePath, isDirectory);

            if (success) {
                this.outputChannel.appendLine(`远程${isDirectory ? '目录' : '文件'}删除成功: ${remotePath}`);
                vscode.window.showInformationMessage(`${isDirectory ? '目录' : '文件'}删除成功: ${path.basename(remotePath)}`);
                return true;
            } else {
                this.outputChannel.appendLine(`远程${isDirectory ? '目录' : '文件'}删除失败`);
                vscode.window.showErrorMessage(`${isDirectory ? '目录' : '文件'}删除失败`);
                return false;
            }
        } catch (error) {
            const errorMsg = `删除远程${isDirectory ? '目录' : '文件'}时发生错误: ${error}`;
            this.outputChannel.appendLine(errorMsg);
            vscode.window.showErrorMessage(errorMsg);
            return false;
        }
    }

    /**
     * 下载远程文件
     * @param remotePath - 远程文件路径
     * @param localPath - 本地保存路径
     * @returns Promise<boolean>
     */
    async downloadFile(remotePath: string, localPath?: string): Promise<boolean> {
        const config = this.configManager.getConfig();
        if (!config) {
            vscode.window.showErrorMessage('请先配置服务器连接信息');
            return false;
        }

        let targetLocalPath = localPath;
        if (!targetLocalPath) {
            const saveUri = await vscode.window.showSaveDialog({
                defaultUri: vscode.Uri.file(path.join(config.localPath, path.basename(remotePath))),
                filters: {
                    'All Files': ['*']
                }
            });
            
            if (!saveUri) {
                return false;
            }
            
            targetLocalPath = saveUri.fsPath;
        }

        this.outputChannel.appendLine(`下载远程文件: ${remotePath} -> ${targetLocalPath}`);

        try {
            const success = await this.deploymentManager.downloadFile(remotePath, targetLocalPath);
            
            if (success) {
                vscode.window.showInformationMessage(`文件下载成功: ${path.basename(remotePath)}`);
                return true;
            } else {
                vscode.window.showErrorMessage(`文件下载失败`);
                return false;
            }
        } catch (error) {
            const errorMsg = `下载文件时发生错误: ${error}`;
            this.outputChannel.appendLine(errorMsg);
            vscode.window.showErrorMessage(errorMsg);
            return false;
        }
    }

    /**
     * 获取当前远程路径
     * @returns string
     */
    getCurrentRemotePath(): string {
        return this.currentRemotePath;
    }

    /**
     * 设置当前远程路径
     * @param remotePath - 远程路径
     */
    setCurrentRemotePath(remotePath: string): void {
        this.currentRemotePath = remotePath;
    }



    /**
     * 显示输出通道
     */
    showOutput(): void {
        this.outputChannel.show();
    }

    /**
     * 清空输出通道
     */
    clearOutput(): void {
        this.outputChannel.clear();
    }
}